﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;

namespace XMK.Framework.DataAccess
{
    /// <summary>
    /// 参数缓存帮助类
    /// </summary>
    public class ParamCacheHelper
    {
        /// <summary>
        /// 存储参数列表
        /// </summary>
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());


        /// <summary>
        /// 从缓存获取参数（若不存在则生成参数列表后缓存并返回）
        /// </summary>
        /// <param name="cacheKey">缓存键值</param>
        /// <param name="setParamCache">生成参数列表的委托</param>
        /// <returns>参数列表</returns>
        public static IDbDataParameter[] GetCachedParameters(string cacheKey, GetDbParamsFun setParamCache)
        {
            IDbDataParameter[] param = GetCachedParameters(cacheKey);
            if (param == null)
            {
                param = setParamCache();
                parmCache[cacheKey] = param;
            }
            return param;
        }
        /// <summary>
        /// 从缓存中获取参数
        /// </summary>
        /// <param name="cacheKey">缓存键值</param>
        /// <returns>参数列表</returns>
        public static IDbDataParameter[] GetCachedParameters(string cacheKey)
        {
            if(!parmCache.ContainsKey(cacheKey))
                return null;
            IDbDataParameter[] cachedParms = (IDbDataParameter[])parmCache[cacheKey];
            
            // If the parameters are in the cache
            IDbDataParameter[] clonedParms = new IDbDataParameter[cachedParms.Length];
            // return a copy of the parameters
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (IDbDataParameter)((ICloneable)cachedParms[i]).Clone();
            return clonedParms;
        }
    }
}
